package com.fly.locks.distributed.memcache;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * MemcachedLockThread
 * 
 * @author 00fly
 * @version [版本号, 2021年8月12日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
public class MemcachedLockThread implements Runnable
{
    private MemcachedLockClient memcachedLock;
    
    public MemcachedLockThread(MemcachedLockClient memcachedLock)
    {
        super();
        this.memcachedLock = memcachedLock;
    }
    
    @Override
    public void run()
    {
        String value = RandomStringUtils.randomNumeric(8);
        if (memcachedLock.add("key", value, new Date(System.currentTimeMillis() + 30 * 1000)) == false)
        {
            log.info("[{}] 报名或抢购失败,请稍后再试! 锁持有者：{}", value, memcachedLock.get("key"));
            return;
        }
        
        StopWatch clock = new StopWatch();
        try
        {
            // 领取成功
            log.info("★★★★★★★★ {} 报名或抢购处理中★★★★★★★★", memcachedLock.get("key"));
            clock.start();
            // 模拟耗时业务操作
            TimeUnit.MILLISECONDS.sleep(RandomUtils.nextInt(10000, 20000));
            clock.stop();
            log.info("{} 运行 {} ms ---------------", memcachedLock.get("key"), clock.getLastTaskTimeMillis());
        }
        catch (InterruptedException e)
        {
            log.error(e.getMessage());
        }
        finally
        {
            memcachedLock.remove("key");
            log.info("释放memcachedLock锁");
        }
    }
}
